﻿
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace CNative.Utilities
{
    public class CacheLock : IDisposable
    {
        private readonly ICacheHelper _cache = null;
        private readonly string key;
        private readonly string token;
        private bool con = false;
        public CacheLock(ICacheHelper cache, string _key, TimeSpan? timeOut = null, bool useLock = true, int lockCounter = 5)
        {
            _cache = cache;
            key = _key;
            token = Environment.MachineName;
            if (useLock == false)
                return;
            timeOut = timeOut ?? TimeSpan.FromSeconds(10);

            var _waittime = TimeSpan.FromMilliseconds(timeOut.Value.TotalMilliseconds / 3);
            ExecUtils.ExecPollyWaitAndRetry<TimeoutException, bool>(() =>
            {
                con = cache.LockTake(key, token, timeOut);
                if (!con)
                {
                    throw new TimeoutException($"CacheLock Exceeded timeout of {timeOut.Value}");
                }
                return con;
            }, lockCounter, _waittime);
        }

        public void Dispose()
        {
            if (con)
            {
                _cache.LockRelease(key, token);
            }
        }
    }
}
